package com.web.listeners.imp;

import org.testng.IClass;
import org.testng.ITestResult;

import com.spira.SpiraTest;
import com.spira.SpiraTestInfo;
import com.spira.SpiraTestRun;
import com.spira.SpiraTestStatus;

public class TestRunFactory {

	private TestRunFactory(){}
	
	public static SpiraTestRun newSpiraTestRun(ITestResult testResult){
		
		SpiraTest testAnnotation = getSpiraTestAnnotation(testResult);
		
		String stackTrace = "";
		SpiraTestStatus status = SpiraTestStatus.PASS;
		if(!testResult.isSuccess()){
			stackTrace = testResult.getThrowable().getMessage();
			status = SpiraTestStatus.FAIL;
		}
		SpiraTestInfo testInfo = getSpiraTestInfo(testAnnotation, stackTrace);
		
		int testId = testAnnotation.testId();
		return new SpiraTestRun(testId, status, testInfo);
	}
	
	private static SpiraTest getSpiraTestAnnotation(ITestResult testResult){
		
		IClass testInstance = testResult.getTestClass();
		Class<?> testClass = testInstance.getRealClass();
		return testClass.getAnnotation(SpiraTest.class);
	}
	
	private static SpiraTestInfo getSpiraTestInfo(SpiraTest testAnnotation, String stackTrace){
		
		String name = testAnnotation.name();
		String message = testAnnotation.message();
		
		return new SpiraTestInfo(name, message, stackTrace);
	}
}
